package com.imooc.demo.Controller;

import com.imooc.demo.Model.UsersVO;
import com.imooc.demo.Model.users;
import com.imooc.demo.Service.UserService;
import com.imooc.demo.Util.IMoocJSONResult;
import com.imooc.demo.Util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
@Api(value = "用户注册登录的接口",tags = {"注册和登录的controller"})
public class RegistLoginController extends BasicController{
    @Resource
    private UserService userService;


    @ApiOperation(value="用户注册",notes = "用户注册的接口")
    @PostMapping("/regist")
    public IMoocJSONResult regist(@RequestBody users user) throws Exception {
        boolean usernameIsExit = userService.queryUsernameIsExist(user.getUsername());
        //用户剧名密码不为空
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名和密码不能为空");
        } else if (!usernameIsExit) {//判断用户名是否存在
            user.setNickname(user.getUsername());
            //user.setFace_image("null");
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            user.setFans_counts(0);
            user.setReceive_like_counts(0);
            user.setFollow_counts(0);
            userService.saveUser(user);
        } else {
            return IMoocJSONResult.errorMsg("用户名已存在，换一个试试");
        }
        user.setPassword("");
//        String uniqueToken= UUID.randomUUID().toString();
//        redis.set(USER_REDIS_SESSION+":"+user.getId(),uniqueToken,1000*60*30);

//        UsersVO userVO=new UsersVO();
//        BeanUtils.copyProperties(user,userVO);
//        userVO.setUserToken(uniqueToken);
        UsersVO userVO=getUserToken(user);
        return IMoocJSONResult.ok(userVO);
    }




    /**
     * 用户登录
     * @param user
     * @return JSONResult
     * @throws Exception
     */
    @ApiOperation(value = "用户登录", notes = "用户登录的接口")
    @PostMapping("/login")
    public IMoocJSONResult Login(@RequestBody users user) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return IMoocJSONResult.errorMsg("用户名密码为空！");
        }
        users result = userService.queryUserForLogin(username,MD5Utils.getMD5Str(password));

        if(result!=null){
            result.setPassword("");
            UsersVO userVO=getUserToken(result);
            return IMoocJSONResult.ok(userVO);
        }else {
            return IMoocJSONResult.errorMsg("用户名或密码不正确，请重试");
        }

    }

    public UsersVO getUserToken(users user) {
        String uniqueToken = UUID.randomUUID().toString();
        redisOperator.set(USER_REDIS_SESSION+":"+user.getId(),uniqueToken,1000*60*30);

        UsersVO userVO=new UsersVO();
        BeanUtils.copyProperties(user,userVO);
        userVO.setUserToken(uniqueToken);
        return userVO;
    }

    /**
     * 用户注销
     * @param userId
     * @return JSONResult
     * @throws Exception
     */
    @ApiOperation(value = "用户注销", notes = "用户注销的接口")
    @ApiImplicitParam(name = "userId",value = "用户Id",required = true,dataType = "String",paramType = "query")
    @PostMapping("/logout")
    public IMoocJSONResult Logout(String userId) throws Exception {

        if (redisOperator.del(USER_REDIS_SESSION + ":" + userId)) {
            return IMoocJSONResult.ok();
        }else {
            return IMoocJSONResult.errorMsg("注销失败，请重试！");
        }
    }
}